#include "timer.h"
#include "assert.h"
#include "common_macros.h"

#include "../sleipner_config.h"
#ifdef _PLATFORM_WII
	#include <revolution/os.h>
#endif //_PLATFORM_WII

#ifdef _PLATFORM_WIN32
	#include <windows.h>
#endif //_PLATFORM_WIN32

#ifdef _PLATFORM_SDL

    #ifdef _SDL2
        #include "SDL2/include/SDL.h"
    #else
        #include "SDL-1.2.13/include/SDL.h"
    #endif

#endif //_PLATFORM_WIN32


using namespace util;


Timer::Timer()
{
    Reset();
	m_LastTime = GetTimeStamp();

}

Timer &		Timer::Instance()
{
    static Timer s_timer;
    return s_timer;
}

Timer::~Timer()
{

}

void	Timer::Tick()
{
	const float	CAP_TIME = 1.0f/10.0f;		// precalculated, so don't worry about the divide
	m_FrameID++;

	float OldTime = m_LastTime;


	m_LastTime = GetTimeStamp();
	float Delta = (float)(m_LastTime-OldTime);

	UTIL_CLAMP(Delta, 0.00f, CAP_TIME);
	m_DeltaTime = (m_DeltaTime*0.9f) + (Delta*0.1f);
	UTIL_CLAMP(m_DeltaTime, 0.00f, CAP_TIME);
	m_CurrentTime += m_DeltaTime;

	// calculate FPS
	m_SecondsCounter += m_DeltaTime;
	m_FrameCounter++;
    if( m_SecondsCounter >= 1.0f )    // ticked into a new second
    {
        m_FPS				= m_FrameCounter / m_SecondsCounter;
        m_FrameCounter		= 0;
        m_SecondsCounter	-= 1.0f;
    }
}

float	Timer::GetTimeStamp()
{
	float	Stamp = 0;
	#ifdef _PLATFORM_WIN32
		LARGE_INTEGER	Time, Freq;
		QueryPerformanceCounter(&Time);
		QueryPerformanceFrequency(&Freq);
		unsigned long	Frequency =(unsigned long) Freq.QuadPart;
		unsigned long	TimeStamp = (unsigned long)Time.QuadPart;
		Stamp = TimeStamp / (float)Frequency;
	#endif
	#ifdef _PLATFORM_WII
		//Stamp = Timer::Instance().Time() + 1/60.0f;
		Stamp = OSGetTick() / float(OS_TIMER_CLOCK);
	#endif
	#ifdef _PLATFORM_SDL
		Stamp = SDL_GetTicks() * 0.001f; 
	#endif

	return Stamp;
}

void Timer::Reset()
{
	m_DeltaTime = 0.0f;
	m_SecondsCounter= 0.0f;
	m_CurrentTime= 0.0f;
	m_FPS= 0.0f;
	m_FrameCounter = 0;
	m_FrameID= 0;
	m_LastTime= 0;
	m_MinPeriod = 1;
}
